﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using System.IO;
using Novacode;
using System.Text;



namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmTestLogController : BaseController
    {
        /// <summary>
        /// 检测日志列表
        /// </summary>
        /// <returns></returns>
        public ActionResult TestLogList(string pageName)
        {
            var vm = new PlmTestLogViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var list = PlmTestlogUIRule.GetAllTestlogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Tl_timestamp", out totalRecord, " Tl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;


            vm.ThePlmTestlogList = list;
        //    return View(vm);
            return String.IsNullOrEmpty(pageName) ? View(vm) : View(pageName, vm);
        }
        /// <summary>
        /// 费用计划-列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return TestLogList("TestLogList");

            ViewBag.Tl_SupervisorName = Request.Form["Tl_SupervisorName"];
            ViewBag.Tl_SupervisionNumber = Request.Form["Tl_SupervisionNumber"];
            ViewBag.Tl_RecordDate = Request.Form["Tl_RecordDate"];
            ViewBag.Tl_ContractNumber = Request.Form["Tl_ContractNumber"];
            string sql = " Tl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            if (ViewBag.Tl_SupervisorName != "")
                sql += " and Tl_TestUnit like '%" + ViewBag.Tl_SupervisorName + "%' ";
            if (ViewBag.Tl_SupervisionNumber != "")
                sql += " and Tl_Number like '%" + ViewBag.Tl_SupervisionNumber + "%' ";
            if (ViewBag.Tl_RecordDate != "")
                sql += " and Tl_RecordDate='" + ViewBag.Tl_RecordDate + "' ";
            if (ViewBag.Tl_ContractNumber != "")
                sql += " and Tl_ContractNumber like '%" + ViewBag.Tl_ContractNumber + "%' ";
            var List = PlmTestlogUIRule.GetAllTestlogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Tl_timestamp", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("TestLogList", new PlmTestLogViewModel { ThePlmTestlogList = List });
        }
        /// <summary>
        /// 检测日志添加
        /// </summary>
        /// <returns></returns>
        public ActionResult TestLogAdd(string target, string id)
        {
            ViewBag.OperationType = target;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.检测日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.检测日志;
            if (target == "add")
            {
                var vm = new PlmTestLogViewModel();
                vm.ThePlmTestlog = new PersonnelLogEntity.Model.PlmTestlogInfo();
                vm.ThePlmTestlog.Tl_UserID = GetLoginUserId;
                vm.ThePlmTestlog.Tl_UserName = GetLoginUserRealName;
                vm.ThePlmTestlog.Tl_RecordDate = DateTime.Now;
                if (GetJCProjectSegmentInfo.Count > 0)
                    vm.ThePlmTestlog.Tl_ContractNumber = GetJCProjectSegmentInfo[0].SEGMENT_CODE;

                vm.ThePlmTestlog.Tl_RecordUser = GetLoginUserRealName;
                vm.ThePlmTestlog.Tl_ProfessionalPosition = GetLoginUserInfo.WorkgroupFullName;
                vm.ThePlmTestlog.Tl_TestUnit = GetLoginUserDepartmentName;
                //附件
                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(PlmTestlogUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;
                return View(vm);
            }
            else
            {
                var signle = PlmTestlogUIRule.GetPlmTestlogById(id);
                //附件
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "TestLog_Rules");//SafeKnowledge_Rules  BizType类型
                ViewBag.AssisId = signle.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
                var vm = new PlmTestLogViewModel { ThePlmTestlog = signle };
                return View(vm);
            }
        }
        /// 检测日志查看
        /// </summary>
        /// <returns></returns>
        public ActionResult TestLogView(string target, string id)
        {
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.检测日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.检测日志;
            var signle = PlmTestlogUIRule.GetPlmTestlogById(id);

            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "TestLog_Rules");//SafeKnowledge_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            var vm = new PlmTestLogViewModel { ThePlmTestlog = signle };
            return View(vm);

        }
        public ActionResult TestLogAddHandle(PlmTestLogViewModel vm)
        {
            if (vm == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "操作失败",
                    }
                };
            }
            dynamic jsonReturn = new ExpandoObject();
            string operation_str = string.Empty;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (vm.OperationType == "add")
                {
                    operation_str = "添加";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmTestlog.Assist_ID = AssistID;
                    vm.ThePlmTestlog.Tl_ID = Guid.NewGuid().ToString();
                    PlmTestlogUIRule.InsertPlmTestlog(vm.ThePlmTestlog);
                }
                if (vm.OperationType == "edit")
                {
                    operation_str = "更新";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmTestlog.Assist_ID = AssistID;
                    PlmTestlogUIRule.UpdatePlmTestlog(vm.ThePlmTestlog);
                }
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = string.Format("{0}成功", operation_str), navTabId = "PersonnelLog.PlmTestLog.TestLogList", rel = "", callbackType = "closeCurrent", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = string.Format("{0}失败", operation_str) };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }


        public ActionResult TestLogDelete(string id)
        {

            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                PlmTestlogUIRule.DeletePlmTestlog(id);
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = "删除成功", navTabId = "PersonnelLog.PlmTestLog.TestLogList", rel = "", callbackType = "", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = "删除失败" };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 检测日志导出
        /// </summary>
        /// <returns></returns>
        public FileResult TestLogExport(string id)
        {
            var signle = PlmTestlogUIRule.GetPlmTestlogById(id);
            string fileName = "检测日志.docx";
            return base.ExportToWord(fileName, signle);

            //string path = Server.MapPath("~/Upload/" + fileName);
            //string savePath = Server.MapPath("~/Upload/Temp/" + Guid.NewGuid().ToString() + fileName);
            //using (DocX docx = DocX.Load(path))
            //{
            //    docx.Bookmarks["Tl_TestUnit0"].SetText(signle.Tl_TestUnit);
            //    docx.Bookmarks["Tl_ContractNumber"].SetText(signle.Tl_ContractNumber);
            //    docx.Bookmarks["Tl_TestRange"].SetText(signle.Tl_TestRange);
            //    docx.Bookmarks["Tl_RecordUser0"].SetText(signle.Tl_RecordUser);

            //    docx.Bookmarks["Tl_ProfessionalPosition"].SetText(signle.Tl_ProfessionalPosition);
            //    docx.Bookmarks["Tl_RecordDate0"].SetText(signle.Tl_RecordDate.ToString("yyyy年MM月dd日"));
            //    docx.Bookmarks["Tl_AuditMan0"].SetText(signle.Tl_AuditMan);
            //    docx.Bookmarks["Tl_Number"].SetText(signle.Tl_Number);
            //    docx.Bookmarks["Tl_TestUnit"].SetText(signle.Tl_TestUnit);
            //    docx.Bookmarks["Tl_RecordUser"].SetText(signle.Tl_RecordUser);
            //    docx.Bookmarks["Tl_RecordDate"].SetText(signle.Tl_RecordDate.ToString("yyyy年MM月dd日"));
            //    docx.Bookmarks["Tl_AuditMan"].SetText(signle.Tl_AuditMan);
            //    docx.Bookmarks["Tl_Weather"].SetText(signle.Tl_Weather);
            //    docx.Bookmarks["Tl_TestContent"].SetText(signle.Tl_TestContent ?? "");
            //    docx.Bookmarks["Tl_ProblemsDispose"].SetText(signle.Tl_ProblemsDispose);
            //    docx.SaveAs(savePath);
            //}
            //fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));
            //FileStream file = new FileStream(savePath, FileMode.Open);
            //return File(file, "application/vnd.ms-word", fileName);
        }
    }
}
